package com.shun.service

import com.shun.commons.ApiUtils
import com.shun.commons.exception.AppException
import com.shun.entity.Machine
import com.shun.entity.Note
import com.shun.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.Update
import org.springframework.stereotype.Service
import java.util.*
import javax.crypto.Mac

/**
 * Created by rainbow on 2017/8/31.
 *一事专注，便是动人；一生坚守，便是深邃！
 */
@Service
class MachineService {

    @Autowired
    private lateinit var mongoTemplate: MongoTemplate


    @Autowired
    private lateinit var utils: ApiUtils

    fun create(machine: Machine, user: User) {
        requireNotNull(machine.machineCode, { "设备编码不能为空" })

        val temp = Machine()
        temp.machineCode = machine.machineCode
        temp.remark = machine.remark
        temp.status = machine.status
        temp.uuid = UUID.randomUUID().toString()
        temp.imageUrl = machine.imageUrl
        temp.machineType = machine.machineType
        temp.user = user
        temp.name = machine.name ?: ""
        temp.terminalNumber = machine.terminalNumber
        temp.createTime = Date()

        temp.searchKey = build(temp)

        mongoTemplate.insert(temp)
    }

    fun list(params: Map<String, Any?>): Any {
        val criteria = Criteria()

        if (params["searchKey"].toString().isNotBlank()) criteria.and("searchKey").regex(params["searchKey"].toString())

        if (params["status"].toString().isNotBlank()) criteria.and("status").`in`(params["status"].toString().split(",").map(String::toInt))

        val query = Query.query(criteria)

        val page = if (params["page"] != null) params["page"].toString().toInt() else 0
        val size = if (params["size"] != null) params["size"].toString().toInt() else 10


        if (page > 0) {
            query.skip((page - 1) * size).limit(size)
        }

        val list = mongoTemplate.find(query, Machine::class.java)

        return if (page > 0) {
            mapOf(
                    "list" to list,
                    "page" to page,
                    "size" to size,
                    "total" to mongoTemplate.count(query, Machine::class.java)
            )
        } else {
            list
        }
    }

    fun modify(machineCode: String, params: Map<String, Any?>) {
        params["status"] ?: throw AppException("参数错误")
        mongoTemplate.findAndModify(Query.query(Criteria("machineCode").`is`(machineCode)), Update().set("status", params["status"].toString().toInt()), Machine::class.java)
    }


    fun save(params: Map<String, String>) {
        requireNotNull(params["machineCode"], { "无效的信息" })

        // val machine = mongoTemplate.findOne(Query.query(Criteria("machineCode").`is`(params["machineCode"])), Machine::class.java)

        mongoTemplate.findAndModify(Query.query(Criteria("machineCode").`is`(params["machineCode"])), Update().set("name", params["name"] as String).set("machineCode", "machineCode"), Machine::class.java)
    }

    fun info(machineCode: String) = mongoTemplate.findOne(Query.query(Criteria("machineCode").`is`(machineCode)), Machine::class.java)

    fun query(machineCode: String) = mongoTemplate.find(Query.query(Criteria("machineCode").regex(machineCode)), Machine::class.java)

    fun build(t: Machine): String? {
        val keys = getSearchKeys(t)
        t.searchKey = if (keys.isNotEmpty()) {
            val first = utils.stringToPinyin(keys[0]!!, "first")
            val full = utils.stringToPinyin(keys[0]!!, "full")
            arrayOf(first.first(), first, full, *keys).distinct().joinToString(",")
        } else {
            ""
        }
        return t.searchKey
    }

    fun getSearchKeys(t: Machine) = arrayOf(t.machineCode!!, t.user!!.username)
}